//
//  PersonalMobileViewController.m
//  安好
//
//  Created by 马晓良 on 14-11-19.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "PersonalMobileViewController.h"

@interface PersonalMobileViewController ()
{
    NSTimer *time;
    NSInteger count;
}
/**
 *  要上传的数据存在此字典中
 */
@property (nonatomic, strong) NSMutableDictionary *uploadInfoDic;

/**
 *  手机号码
 */
@property (strong, nonatomic) IBOutlet UITextField *mobileTextField;
/**
 * 验证信息
 */
@property (strong, nonatomic) IBOutlet UITextField *validationTextField;
/**
 *  获取验证码按钮
 */
@property (strong, nonatomic) IBOutlet UIButton *getVerificationCodeButton;

/**
 *  验证手机按钮
 */
@property (strong, nonatomic) IBOutlet UIButton *verifyMobilePhone;
@property (strong, nonatomic) IBOutlet UILabel *contentLabel;


@end

@implementation PersonalMobileViewController
- (NSMutableDictionary *)uploadInfoDic{
    if (_uploadInfoDic == nil) {
        self.uploadInfoDic = [NSMutableDictionary dictionary];
    }
    return _uploadInfoDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"手机号码";
    [self setNaviBarAttribute];
    self.contentLabel.hidden = YES;
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.mobileTextField.keyboardType = UIKeyboardTypePhonePad;
    self.validationTextField.keyboardType = UIKeyboardTypePhonePad;
    [self.mobileTextField becomeFirstResponder];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// block 传值
- (void)getTextFieldInfo:(backMobile)string{
    self.mobileInfo = string;
}


- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 23, 23);
    [rightButton setImage:[UIImage imageNamed:@"公用_完成"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(handleRightButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

/**
 *  返回
 */
- (void)handleLeftButtonAction{
//    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  完成(返回并传值)
 */
- (void)handleRightButtonAction{
    self.mobileInfo(self.mobileTextField.text);
    NSString * postURL = [NSString stringWithFormat:@"%@user/changeuser/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"mobile":self.mobileTextField.text};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
        }else{
            MyNSLog("======%@========", [responseObject objectForKey:@"msg"]);
        }
    } failure:nil];
}

/**
 *  获取验证码
 */
- (IBAction)getVerificationCodeButtonAction:(id)sender {
    if ([self checkPhoneNumber:self.mobileTextField.text]) {
        self.getVerificationCodeButton.userInteractionEnabled = NO;
        [self _parsePersonalDataSource:kBaseURL];
    }

}


/**
 * 手机验证
 */
- (IBAction)verifyMobilePhoneButtonAction:(id)sender{
    MyNSLog("验证手机");
    if (self.mobileTextField.text.length<=0) {
        alertContent(@"请输入电话号码");
        return;
    }
    if (self.validationTextField.text.length<=0) {
        alertContent(@"请输入验证码");
        return;
    }
    self.mobileInfo(self.mobileTextField.text);
    NSString * postURL = [NSString stringWithFormat:@"%@user/checkphone/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"mobile":self.mobileTextField.text,@"vercode":self.validationTextField.text};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
        }else{
            MyNSLog("======%@========", [responseObject objectForKey:@"msg"]);
        }
    } failure:nil];
}


- (void)_parsePersonalDataSource:(NSString *)urlString{
    // 获取url地址
    NSString * postURL = [NSString stringWithFormat:@"%@docuser/sms/",urlString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"phone":self.mobileTextField.text,@"action":@"user"};
    MyNSLog("%@", self.mobileTextField.text);
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
            self.getVerificationCodeButton.userInteractionEnabled=YES;
        }else if([statusString isEqualToString:@"1"]){
            count = 59;
            time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dotime) userInfo:nil repeats:YES];
            self.getVerificationCodeButton.userInteractionEnabled = NO;
        }
    } failure:nil];
}


/**
 *  判断手机号是否符合规则
 */
- (BOOL)checkPhoneNumber:(NSString *)tel
{
    if ([tel length] == 0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"手机号不能为空", nil) delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    NSString *regex = @"^((13[0-9])|(147)|(145)|(15[^4,\\D])|(18[0-9])|(17[6-8]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:tel];
    if (!isMatch) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    return YES;
}

-(void)dotime
{
    if (count>-1) {
//        [self.getVerificationCodeButton setTitle:[NSString stringWithFormat: @"%d秒重发验证码",count] forState: UIControlStateNormal];
        [self.getVerificationCodeButton setTitle:[NSString stringWithFormat: @""] forState: UIControlStateNormal];
        self.contentLabel.hidden = NO;
        self.contentLabel.text = [NSString stringWithFormat:@"%ld秒重发验证码",(long)count];
        count--;
    }else
    {
        [time invalidate];
        self.contentLabel.hidden = YES;
        [self.getVerificationCodeButton setTitle:@"重发验证码" forState: UIControlStateNormal];
        self.getVerificationCodeButton.userInteractionEnabled = YES;
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
